/**
 * 
 */
package com.arsl.client.presenter;

import com.arsl.client.PaperaziServiceAsync;
import com.arsl.client.event.LoginEvent;
import com.arsl.client.view.SignInPanel;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;

/**
 * @author NuwanSam
 * 
 */
public class SignInPanelPresenter implements Presenter {

	private PaperaziServiceAsync rpcService;
	private HandlerManager eventBus;
	private SignInPanel viewer;

	public SignInPanelPresenter(PaperaziServiceAsync rpcService,
			HandlerManager eventBus, SignInPanel signInPanel) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.viewer = signInPanel;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.arsl.client.presenter.Presenter#go(com.google.gwt.user.client.ui.
	 * HasWidgets)
	 */
	@Override
	public void go(HasWidgets container) {
		container.clear();
		container.add(viewer);
	}

	public void trySignIn(final String email, final String pass) {
		AsyncCallback<Integer[]> callback = new AsyncCallback<Integer[]>() {

			@Override
			public void onSuccess(Integer[] result) {
				if (result[0] == 0)
					Window.alert("Login Failed");
				else
					signIn(email, result[1], result[2]);
			}

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}
		};
		rpcService.signIn(email, pass, callback);
	}

	protected void signIn(String email, Integer userId, Integer publisherId) {
		LoginEvent event = new LoginEvent();
		event.setEventType(LoginEvent.LOGIN);
		event.setEmail(email);
		event.setUserId(userId);
		event.setPublisherId(publisherId);
		eventBus.fireEvent(event);
	}

}
